package org.iabako.client.ui.form.extranet.passwordreminder;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.HTMLPanel;
import org.iabako.client.config.page.PageConfigEnum;
import org.iabako.client.navigation.NavigationController;
import org.iabako.client.tools.IabakoAsyncCallback;
import org.iabako.client.tools.Messages;
import org.iabako.client.ui.form.extranet.EmailVerificationForm;
import org.iabako.client.ui.layout.field.Button;
import org.iabako.client.ui.layout.field.IField;
import org.iabako.client.ui.layout.field.InputTextPassword;
import org.iabako.client.ui.layout.field.LabelText;
import org.iabako.client.ui.layout.widget.dialogbox.IabakoDialogBox;
import org.iabako.client.ui.layout.widget.validation.ValidationMessage;
import org.iabako.shared.entity.business.AbstractEntity;
import org.iabako.shared.entity.user.User;
import org.iabako.shared.iservice.user.SignUpServiceAsync;
import org.iabako.shared.tools.GenericTools;

import java.util.List;

/**
 * Created by jose on 06/01/15.
 */
public abstract class PasswordReminderForm extends EmailVerificationForm {

    interface MyUiBinder extends UiBinder<HTMLPanel, PasswordReminderForm> {
    }

    protected MyUiBinder binderForm = GWT.create(MyUiBinder.class);

    protected final SignUpServiceAsync signUpServiceAsync = SignUpServiceAsync.Util.getInstance();

    @UiField
    HTMLPanel newPasswordPanel;
    @UiField
    InputTextPassword newPassword;
    @UiField
    InputTextPassword newPasswordAgain;
    @UiField
    Button goAheadNewPassword;
    @UiField
    LabelText emailVerifiedText;

    private int attempts;
    User user;

    public PasswordReminderForm() {
        simplePopup = true;
        setForm(binderForm, PageConfigEnum.SignUp, null);

        userExistsVerification = true;

        goAheadEmailHandler();
        goAheadVerificationHandler();
        goAheadNewPasswordHandler();
    }

    @Override
    protected void customSendKeyCodeAction(User result) {
        if (result == null) {
            ValidationMessage.getFirstFromDOM().showErrorMessage(true, true, "validation_password_reminder_no_user_error");
            return;
        }
        user = result;
        emailPanel.setVisible(false);

        initializeEmailVerificationPanel("password_reminder_email_verification_text", "password_reminder_email_verification_help");
        ValidationMessage.getFirstFromDOM().clear();
        emailVerificationPanel.setVisible(true);
    }

    @Override
    protected void customVerifyKeyCodeAction(Boolean result) {
        attempts++;

        if (result != null && result) {

            emailVerificationPanel.setVisible(false);
            emailVerifiedText.setLabel(Messages.getLabel("password_reminder_email_verified", user.getFirstName()));
            ValidationMessage.getFirstFromDOM().clear();
            newPasswordPanel.setVisible(true);

        } else if (attempts < 3) {

            keyCode.addErrorMessage(keyCode, false, "validation_key_code_error");

        } else {
            NavigationController.getInstance().closePopups();
            NavigationController.getInstance().show(new IabakoDialogBox("sign_up_attempts_limit_error_title", "sign_up_attempts_limit_error_message"));
        }
    }

    public boolean isNewPasswordAgainValid() {
        return newPassword.getValue() != null
                && newPassword.getValue().equals(newPasswordAgain.getValue());
    }

    private void goAheadNewPasswordHandler() {
        newPassword.getInputField().addBlurHandler(new BlurHandler() {
            public void onBlur(BlurEvent event) {
                if (newPasswordAgain.getValue() != null && !isNewPasswordAgainValid()) {
                    newPasswordAgain.addErrorMessage(newPasswordAgain, true, "passwords_not_equal");
                } else {
                    newPasswordAgain.clearErrorMessage(newPasswordAgain, "passwords_not_equal");
                }
            }
        });

        newPasswordAgain.getInputField().addBlurHandler(new BlurHandler() {
            public void onBlur(BlurEvent event) {
                if (newPasswordAgain.getValue() != null && !isNewPasswordAgainValid()) {
                    newPasswordAgain.addErrorMessage(newPasswordAgain, true, "passwords_not_equal");
                } else {
                    newPasswordAgain.clearErrorMessage(newPasswordAgain, "passwords_not_equal");
                }
            }
        });

        goAheadNewPassword.getButton().addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                if (GenericTools.isEmpty(newPassword.getValue(), newPasswordAgain.getValue())) {
                    newPassword.addErrorMessage(newPassword, true, "");
                    newPasswordAgain.addErrorMessage(newPasswordAgain, true, "");
                    ValidationMessage.getFirstFromDOM().showErrorMessage(true, true, "validation_form_mandatory_red_fields_error");
                    return;
                }
                if (!isNewPasswordAgainValid()) {
                    newPasswordAgain.addErrorMessage(newPasswordAgain, true, "passwords_not_equal");
                    return;
                }

                user.setPassword(GenericTools.getMd5(newPassword.getValue()));

                signUpServiceAsync.saveUser(user, new IabakoAsyncCallback<User>() {
                    public void onSuccess(User result) {

                        NavigationController.getInstance().closePopups();

                        NavigationController.getInstance().show(new IabakoDialogBox(
                                "password_reminder_password_modified_title",
                                Messages.getLabel("password_reminder_password_modified_text", user.getFirstName()),
                                true, "password_reminder_password_modified_text_ok"));

                        super.onSuccess(result);
                    }
                });
            }
        });
    }

    @Override
    protected List<IField> getMandatoryFields() {
        return null;
    }

    @Override
    protected AbstractEntity getEntity() {
        return null;
    }

    @Override
    public boolean validate() {
        return false;
    }
}
